<script setup lang="ts">

import {ref} from "vue";
import type {Carousel} from "@/net/controller/carousel-controller.ts";
import {getAllCarousels, getEmptyCarousel, saveOrUpdateCarousel} from "@/net/controller/carousel-controller.ts";

const carousels = ref<Carousel[]>([])

async function refreshData() {
  carousels.value = await getAllCarousels()
}

refreshData()

const showAddDialog = ref(false)
const addDialogData = ref<Carousel>(getEmptyCarousel())

function openAddCarouselDialog(carouselId: Carousel) {
  showAddDialog.value = true
  addDialogData.value = carouselId
}

function confirmAddCarousel() {
  saveOrUpdateCarousel(addDialogData.value).then(async () => {
    ElMessage.success("添加成功")

    await refreshData()
  }).finally(() => {
    showAddDialog.value = false
  })
}

</script>

<template>
  <main class="flex flex-vertical">
    <div>
      <el-button size="default" type="info" @click="refreshData()">刷新</el-button>
      <el-button size="default" type="primary" @click="openAddCarouselDialog(getEmptyCarousel())">添加</el-button>
    </div>

    <el-table :data="carousels" style="margin-top: 1rem">
      <el-table-column fixed prop="carouselId" label="轮播图ID" />
      <el-table-column prop="imageUrl" label="图片地址" />
      <el-table-column prop="redirectUrl" label="跳转地址" />
      <el-table-column prop="priority" label="优先级" />
      <el-table-column prop="isActive" label="是否启用" />
      <el-table-column prop="expireTime" label="过期时间" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="openAddCarouselDialog(scope.row)">
            编辑
          </el-button>
          <el-button link type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="showAddDialog" title="添加/编辑轮播图" width="600">
      <el-form size="default" :model="addDialogData" label-width="auto" style="max-width: 600px" label-position="top">
        <el-form-item label="图片地址">
          <el-input v-model="addDialogData.imageUrl" />
        </el-form-item>
        <el-form-item label="跳转地址">
          <el-input v-model="addDialogData.redirectUrl" />
        </el-form-item>
        <el-form-item label="优先级">
          <el-input v-model="addDialogData.priority" />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-input v-model="addDialogData.isActive" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div>
          <el-button size="default" @click="showAddDialog = false">取消</el-button>
          <el-button size="default" type="primary" @click="confirmAddCarousel()">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </main>
</template>

<style scoped>

</style>